package com.pyb.java.network;


import com.pyb.java.network.interceptor.HeadersInterceptor;
import com.pyb.java.network.interceptor.LogInterceptor;
import com.pyb.java.network.interceptor.PlusHttpLoggingInterceptor;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManger {

    /**
     * 保存一个retrofit的实例，通过（baseUrl来获取）
     */
    private HashMap<String, Retrofit> mRetrofitHashMap = new HashMap<>();

    private static final int DEFAULT_MILLISECONDS = 10;             //默认的超时时间


    /**
     * 内部类单例设计模式
     */

    private RetrofitManger() {
    }

    private static class RetrofitMangerInstance {
        private final static RetrofitManger RETROFIT_MANGER = new RetrofitManger();
    }

    public static RetrofitManger getInstance() {
        return RetrofitMangerInstance.RETROFIT_MANGER;
    }

    private Retrofit getRetrofit(String baseUrl) {

        Retrofit retrofit;

        if (mRetrofitHashMap.containsKey(baseUrl)) {
            retrofit = mRetrofitHashMap.get(baseUrl);
        } else {
            retrofit = createRetrofit(baseUrl);
            mRetrofitHashMap.put(baseUrl,retrofit);
        }

        return retrofit;
    }

    /**
     * @Params :创建Retrofit
     * @Author :zhaohuiming
     * @Date :2019/12/10
     */
    private Retrofit createRetrofit(String baseUrl) {
        OkHttpClient httpClient = new OkHttpClient().newBuilder()
                .readTimeout(DEFAULT_MILLISECONDS, TimeUnit.SECONDS)//设置读取超时时间
                .connectTimeout(DEFAULT_MILLISECONDS, TimeUnit.SECONDS)//设置请求超时时间
                .writeTimeout(DEFAULT_MILLISECONDS, TimeUnit.SECONDS)//设置写入超时时间
                .addInterceptor(new HeadersInterceptor())//添加公共头信息
                .addInterceptor(new LogInterceptor())//添加打印拦截器
                .retryOnConnectionFailure(false)
                .addNetworkInterceptor(new PlusHttpLoggingInterceptor())
                //设置出现错误进行重新连接。
                .build();

        return new Retrofit.Builder()
                .client(httpClient)
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }


    /**
     * 根据各业务接口  获取不同的retrofit service接口对象
     */

    public <T> T createService(Class<T> tClass) {
        return getRetrofit(NetBaseApi.getBaseUrl()).create(tClass);
    }
}
